﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace LuDragon.Common.Utils
{
    /// <summary>
    /// Cookie帮助类
    /// </summary>
    public class CookieHelper
    {
        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="name">Cookie名称</param>
        /// <param name="value">Cookie值</param>
        /// <param name="expires">有效时间 -1表示设置已过期，1表示永久有效，0和其它负数都表示不设有效时间，大于等于2表示具体有效秒数</param>
        public static void SetCookie(string name, string value, int expires)
        {
            var context = HttpContext.Current;
            var cookie = new HttpCookie(name);
            if (context.Request.Cookies[name] != null)
            {
                cookie = context.Request.Cookies[name];
            }
            cookie.Value = HttpUtility.UrlEncode(value);
            if (expires == 1)
            {
                cookie.Expires = DateTime.MaxValue;
            }
            else
            {
                cookie.Expires = DateTime.Now.AddSeconds(expires);
            }
            if (CheckCookieLength(cookie))
            {
                context.Response.Cookies.Add(cookie);
            }
        }

        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetCookie(string name)
        {
            var context = HttpContext.Current;
            if (context.Request.Cookies[name] == null)
            {
                return null;
            }
            else
            {
                return HttpUtility.UrlDecode(context.Request.Cookies[name].Value);
            }
        }

        /// <summary>
        ///  删除Cookie
        /// </summary>
        public static void DeleteCookie(string name)
        {
            var context = HttpContext.Current;
            var cookie = context.Request.Cookies[name];
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddYears(-3);
            }
            context.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// Cookie最大保存4095字节长度
        /// </summary>
        /// <param name="cookie"></param>
        /// <returns></returns>
        private static bool CheckCookieLength(HttpCookie cookie)
        {
            int length = Encoding.Default.GetBytes(cookie.Value).Length;
            if (length > 4095)
            {
                throw new Exception("cookie大小超过了4095");
            }
            else
            {
                return true;
            }
        }
    }
}
